package traefik_minio_vue

import (
	"context"
	"net/http"
	"net/url"
	"strings"
)

type Config struct {
	Static      []string `json:"static,omitempty"`
	ExtraStatic []string `json:"extraStatic,omitempty"`
	Prefix      string   `json:"prefix,omitempty"`
}

func CreateConfig() *Config {
	return &Config{}
}

var _defaultStatic = []string{"static", "statics", "js", "css", "img", "imgs", "images", "image", "fonts", "font", "favicon.ico"}

const _defaultIndex = "/index.html"

type VUE struct {
	next        http.Handler
	extraStatic []string
	prefix      string
}

func (v *VUE) IsStatic(path string) bool {
	statics := append(_defaultStatic, v.extraStatic...)
	for i := 0; i < len(statics); i++ {
		static := "/" + statics[i]
		if !strings.Contains(static, ".") {
			static = static + "/"
		}
		if strings.Contains(path, static) {
			return true
		}
	}
	return false
}

func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {

	return &VUE{
		next:        next,
		extraStatic: config.ExtraStatic,
		prefix:      config.Prefix,
	}, nil
}

func (v *VUE) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	currentPath := req.URL.RawPath
	if currentPath == "" {
		currentPath = req.URL.EscapedPath()
	}
	didChange := false
	if !v.IsStatic(currentPath) {
		currentPath = _defaultIndex
		didChange = true
	}
	if v.prefix != "" {
		currentPath = v.prefix + currentPath
		didChange = true
	}

	if didChange {
		req.URL.RawPath = currentPath
		req.URL.Path, _ = url.PathUnescape(req.URL.RawPath)
		req.RequestURI = req.URL.RequestURI()
	}

	v.next.ServeHTTP(res, req)
}
